package org.dromara.system.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import org.dromara.common.excel.utils.ConvertUtil;
import org.dromara.common.mybatis.core.page.CustomConditions;
import org.dromara.system.domain.bo.SysConfigBo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springdoc.core.annotations.ParameterObject;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;
import org.dromara.system.domain.vo.SysCommonFieldsVo;
import org.dromara.system.domain.bo.SysCommonFieldsBo;
import org.dromara.system.service.ISysCommonFieldsService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 常用字段
 *
 * @author yilong.fu
 * @date 2024-11-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/system/commonFields")
public class SysCommonFieldsController extends BaseController {

    private final ISysCommonFieldsService sysCommonFieldsService;
    private final ISysOssService ossService;

    /**
     * 查询常用字段列表
     */
    @SaCheckPermission("system:commonFields:list")
    @PostMapping("/list")
    public TableDataInfo<SysCommonFieldsVo> list(@RequestBody JSONObject obj) {
        SysCommonFieldsBo bo = obj.toBean(SysCommonFieldsBo.class);
        CustomConditions pageQuery = obj.toBean(CustomConditions.class);
        return sysCommonFieldsService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出常用字段列表
     */
    @SaCheckPermission("system:commonFields:export")
    @Log(title = "常用字段", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@ParameterObject SysCommonFieldsBo bo, HttpServletResponse response) throws IOException {
        List<SysCommonFieldsVo> list = sysCommonFieldsService.queryList(bo);
        ExcelUtil.write(response, "常用字段", "信息列表", SysCommonFieldsVo.class, list);
    }

    /**
     * 获取常用字段详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("system:commonFields:query")
    @GetMapping("/{id}")
    public R<SysCommonFieldsVo> getInfo(@NotNull(message = "主键不能为空")
                                        @PathVariable Long id) {
        return R.ok(sysCommonFieldsService.queryById(id));
    }

    /**
     * 新增常用字段
     */
    @SaCheckPermission("system:commonFields:add")
    @Log(title = "常用字段", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Long> add(@Validated(AddGroup.class) @RequestBody SysCommonFieldsBo bo) {
        boolean flag = sysCommonFieldsService.insertByBo(bo);
        if (!flag) {
            return R.fail();
        }
        return R.ok(bo.getId());
    }

    /**
     * 修改常用字段
     */
    @SaCheckPermission("system:commonFields:edit")
    @Log(title = "常用字段", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysCommonFieldsBo bo) {
        return toAjax(sysCommonFieldsService.updateByBo(bo));
    }

    /**
     * 删除常用字段
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:commonFields:remove")
    @Log(title = "常用字段", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(sysCommonFieldsService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 获取常用字段导入模板
     */
    @PostMapping("/getImportTemplate")
    @Operation(summary = "获得常用字段导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<SysCommonFieldsVo> list = Arrays.asList();
//        ExcelUtil.exportExcel(list, "信息列表", SysCommonFieldsVo.class, response);
        // 输出
        ExcelUtil.write(response, "常用字段导入模板", "信息列表", SysCommonFieldsVo.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入常用字段基本信息")
    @Parameters({@Parameter(name = "file", description = "Excel 文件", required = true), @Parameter(name = "mode", description = "导入模式1更新2追加3覆盖", example = "1"),
        @Parameter(name = "updatePart", description = "部分更新，默认为 true", example = "true")})
    @SaCheckPermission("system:commonFields:add")
    public R<Map<String, Object>> importExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file, @RequestParam(value = "mode") Integer mode,
                                              @RequestParam(value = "updatePart", required = false, defaultValue = "false") Boolean updatePart) throws Exception {
        List<SysCommonFieldsVo> list = ExcelUtil.read(file, SysCommonFieldsVo.class);
        ConvertUtil<SysCommonFieldsVo> convertUtil = new ConvertUtil<>(SysCommonFieldsVo.class);
        List<SysCommonFieldsVo> dynamicRuleCreateReqVOList = convertUtil.invoke(list).getDataList();
        List<SysCommonFieldsVo> errorList = sysCommonFieldsService.importList(dynamicRuleCreateReqVOList, mode, updatePart);

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("errorCount", errorList.size());
        if (!errorList.isEmpty()) {
            String fileName = "导入错误数据" + LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) + ".xlsx";
            ByteArrayOutputStream outputStream = ExcelUtil.writeStream("错误列表", errorList);
            SysOssVo sysOssVo = ossService.upload(outputStream, fileName);
            returnMap.put("errorFile", sysOssVo.getUrl());
        }

        return R.ok(returnMap);
    }

}
